﻿using System;
using System.Collections.Generic;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Xml.Serialization;
using Wicresoft.Logger;
using Wicresoft.Task.Common;

namespace ARSys.Service
{
    static class SchedulerHelper
    {
        public static IEnumerable<ITask> GetAllTasks()
        {
            schedule s = GetSchedule("schedule.xml");

            foreach (var t in s.task)
            {
                ITask task = null;

                try
                {
                    task = Assembly.Load(t.assembly).
                                    CreateInstance(t.inherit) as ITask;
                }
                catch (Exception e)
                {
                    Log.Exception("Scheduler", e);
                }

                if (task != null)
                {
                    task.Name = t.name;
                    task.SleepInterval = t.interval * 1000;

                    IDictionary<string, object> bag = new ExpandoObject();
                    foreach (var p in t.bag)
                    {
                        bag[p.key] = p.value;
                    }
                    task.Bag = bag;

                    yield return task;
                }
            }
        }


        public static schedule GetSchedule(string source)
        {
            var s = XmlDeserialize<schedule>(File.ReadAllBytes(source));
            return s;
        }


        private static T XmlDeserialize<T>(byte[] buffer) where T : class
        {
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            using (StreamReader sr = new StreamReader(new MemoryStream(buffer)))
            {
                return serializer.Deserialize(sr) as T;
            }
        }
    }
}
